/* 2017-12-6 11:11:44 | 修改 木遥（QQ：516584683） */
//模块：
mars3d.widget.bindClass(mars3d.widget.BaseWidget.extend({
    options: {
        //弹窗
        view: {
            type: "window",
            url: "view.html",
            windowOptions: {
                width: 250,
                position: {
                    "top": 5,
                    "right": 5,
                    "bottom": 5
                }
            }
        },
    },
    drawControl: null,
    beginFly:false,
    deleteStatus:false,
    //初始化[仅执行1次]
    create: function () {

        this.drawControl = new mars3d.Draw(this.viewer, { hasEdit: true });

        //事件监听
        var that = this;
        this.drawControl.on(mars3d.draw.event.DrawCreated, function (e) {
            var entity = e.entity;
            if (entity._attribute.attr.id == null || entity._attribute.attr.id == "")
                entity._attribute.attr.id = (new Date()).format("MMddHHmmss");

            if (that.viewWindow)
                that.viewWindow.plotlist.plotEnd();
        });
        this.drawControl.on(mars3d.draw.event.EditStart, function (e) {
            var entity = e.entity;
            that.startEditing(entity);
        });
        this.drawControl.on(mars3d.draw.event.EditMovePoint, function (e) {
            var entity = e.entity;
            that.startEditing(entity);
        });
        this.drawControl.on(mars3d.draw.event.EditRemovePoint, function (e) {
            var entity = e.entity;
            that.startEditing(entity);
        });
        this.drawControl.on(mars3d.draw.event.EditStop, function (e) {

            var entity = e.entity;
            that.stopEditing(entity);

            var name = entity._attribute.attr.name;

            if(!that.deleteStatus){
                if(!name) {
                    return
                }else{
                    that.saveEntity(entity);
                }
            }
        });

        this.getList();
    },
    viewWindow: null,
    //每个窗口创建完成后调用
    winCreateOK: function (opt, result) {
        this.viewWindow = result;
    },
    //激活插件
    activate: function () {
        this.drawControl.hasEdit(true);
        this.drawControl.setVisible(true);
        this.dealQingxie();
    },
    qingxielayer: null,
    dealQingxie: function() {
        viewer.mars.updateTerrainProvider(false);
        //start
        //start
        //url: "http://10.190.54.56:7763/TILE_3D_MODEL/futian_v1/tileset.json",
        const mapurl = new Cesium.Resource({
            url: "http://10.190.54.56:7763/TILE_3D_MODEL/futian/tileset.json",
            headers: { "szvsud-license-key": "eTG1UGBSvr4HdQnLecWX1s8GA4NWjLe8Rp8eI9ztla05D5mPYyi3rvVRX0RGjm5G" }
        });
        if(this.qingxielayer){
            return;
        }
         this.qingxielayer = new Cesium.Cesium3DTileset({
            url: mapurl, // 你的倾斜摄影服务发布地址  // "http://localhost/xmhtileset/tileset.json",
            skipLevelOfDetail: true,
            preferLeaves: true,
            maximumScreenSpaceError: 16,
            skipLevels: 1,
        });
        this.qingxielayer.readyPromise.then(tileSet => {
            viewer.scene.primitives.add(tileSet); // 将倾斜摄影实体加载到地图上

            viewer.zoomTo(tileSet);
        });
        viewer.showtileset = true;
    },
    //将3d模型删除
    removeQinxie: function() {
        viewer.mars.updateTerrainProvider(true);
        viewer.scene.primitives.remove(this.qingxielayer); //销毁
        viewer.showtileset = false;
        // qingxiemaplayer && qingxiemaplayer.setVisible(true);
    },
    //释放插件
    disable: function () {
        this.viewWindow = null;
        // this.removeQinxie();
        this.drawControl.stopDraw();

        if (this.lastEditEntity) {
            this.lastEditEntity._polyline.show = false;
            this.lastEditEntity._attribute.style.show = false;
            this.lastEditEntity = null;
        }

        this.drawControl.hasEdit(false);
        this.drawControl.setVisible(false);
    },

    //开始标记
    startDraw: function (defval) {
        //console.log(JSON.stringify(defval));
        this.drawControl.startDraw(defval);
    },
    startEditingById: function (id) {
        var entity = this.drawControl.getEntityById(id);
        if (entity == null) return;

        this.viewer.flyTo(entity);

        this.drawControl.startEditing(entity);
    },
    lastEditEntity: null,
    startEditing: function (entity) {
        //编辑时只显示本身路线，其他路线隐藏
        if (this.lastEditEntity) {
            this.lastEditEntity._polyline.show = false;
            this.lastEditEntity._attribute.style.show = false;
            this.lastEditEntity = null;
        }
        this.lastEditEntity = entity;

        entity._polyline.show = true;
        entity._attribute.style.show = true;

        var lonlats = this.drawControl.getCoordinates(entity);
        this.viewWindow.plotEdit.startEditing(entity.attribute, lonlats);
    },
    stopEditing: function (layer) {
        if (this.viewWindow)
            this.viewWindow.plotEdit.stopEditing();
    },
    //更新图上的属性
    updateAttr2map: function (attr) {
        this.drawControl.updateAttribute(attr);
    },
    //更新图上的几何形状、坐标等
    updateGeo2map: function (coords, withHeight) {
        var positions = [];
        if (withHeight) {
            for (var i = 0; i < coords.length; i += 3) {
                var point = Cesium.Cartesian3.fromDegrees(coords[i], coords[i + 1], coords[i + 2]);
                positions.push(point);
            }
        }
        else {
            for (var i = 0; i < coords.length; i += 2) {
                var point = Cesium.Cartesian3.fromDegrees(coords[i], coords[i + 1], 0);
                positions.push(point);
            }
        }
        this.drawControl.setPositions(positions);

        if (positions.length <= 3) {
            this.centerCurrentEntity();
        }

        return positions;
    },
    centerCurrentEntity: function () {
        var entity = this.drawControl.getCurrentEntity();
        if (entity == null) return;
        this.viewer.flyTo(entity);
    },
    //文件处理
    getGeoJson: function () {
        return this.drawControl.toGeoJSON();
    },
    jsonToLayer: function (json, isClear, isFly) {
        if (json == null) return;

        return this.drawControl.jsonToEntity(json, isClear, isFly);
    },
    deleteAll: function () {
        this.drawControl.deleteAll();
        this.deleteAllData();
    },
    deleteEntity: function (id) {
        var entity = this.drawControl.getEntityById(id);
        // if (entity == null) return;

        this.delEntity(id);
        this.drawControl.deleteEntity(entity);
    },
    deleteCurrentEntity: function () {

        var entity = this.drawControl.getCurrentEntity();
        if (entity == null) return;

        this.delEntity(entity._attribute.attr.id);
        this.drawControl.deleteEntity(entity);
    },
    hasEdit: function (val) {
        this.drawControl.hasEdit(val);
    },

    //数据保存处理
    storageName: "marsgis_roam",
    arrFlyTable: [],
    getList: function () {
            var that = this;

            var scene_id=this.config.sceneId
            var roamList;
            this.arrFlyTable = [];
            $.ajax({
                url: "/one/scene/navigation/route/all"+'?sceneId='+scene_id,
                type: "GET",
                dataType: "json",
                contentType: "application/json; charset=UTF-8",
                success: function(result){
                    if (result.errorCode === '401') {
                        loginStatusIntercept(result.msg)
                        return
                    }
                    if(result.errorCode==0){
                        roamList=result.data;
                        roamList.forEach(item=>{
                            item.navigationContent = JSON.parse(item.navigationContent)
                            item = {...item.navigationContent,...item};
                            that.arrFlyTable.push(item)
                        });
                        that.showData(that.arrFlyTable);
                        that.beginFly = false;
                        if (that.viewWindow)
                            that.viewWindow.tableWork.loadData(that.arrFlyTable);
                    }else{
                        layer.msg("获取数据列表失败");
                    }
                }
            });
    },
    showData: function (arr) { //加载历史保存数据
        var arrjson = [];
        for (var i = 0; i < arr.length; i++) {
            var item = arr[i];
            item.properties.style.show = false;

            var json = {
                type: "Feature",
                properties: item.properties,
                geometry: item.geometry
            };
            json.properties.attr.id = item.id;
            json.properties.attr.name = item.name;

            arrjson.push(json);
        }
        this.drawControl.jsonToEntity({ type: "FeatureCollection", features: arrjson }, true, false);
    },
    deleteAllData: function () {
        this.arrFlyTable = [];
        haoutil.storage.add(this.storageName, JSON.stringify(this.arrFlyTable));
        if (this.isActivate && this.viewWindow != null)
            this.viewWindow.tableWork.loadData(this.arrFlyTable);
    },
    delEntity: function (id) {
        this.deleteStatus = true;
        that = this;
        $.ajax({
            url: "/one/scene/navigation/route"+"?ids="+id,
            type: "DELETE",
            dataType: "json",
            contentType: "application/json; charset=UTF-8",
            success: function(result){
                if (result.errorCode === '401') {
                    loginStatusIntercept(result.msg)
                    return
                }
                // console.log(res);
                if(result.errorCode==0){
                    that.getList();
                    this.deleteStatus = false;
                    layer.msg("删除成功");
                }else{
                    layer.msg("删除失败");
                }
            }
        });
        this.deleteStatus = false;

    },
    saveEntity: function (entity) {
        if (entity._attribute.attr.id == null || entity._attribute.attr.id == "")
            entity._attribute.attr.id = (new Date()).format("MMddHHmmss");

        if (entity._attribute.attr.name == null || entity._attribute.attr.name == "")
            entity._attribute.attr.name = '路线' + entity._attribute.attr.id;

        var json = this.drawControl.toGeoJSON(entity);
        if (json.geometry.coordinates.length < 2) {//路线点数小于2个
            layer.msg("路线点数小于2个")
            return;
        }
        that = this;


        var item = {
            id: json.properties.attr.id,
            name: json.properties.attr.name,
            remark: json.properties.attr.remark,
            geometry: json.geometry,
            properties: json.properties,
        };
        //场景漫游
        if(that.beginFly){
            that.toRoamFly(item);
        }
        //修改飞行路径
        var isFind = false;
        for (var index = this.arrFlyTable.length - 1; index >= 0; index--) {
            if (this.arrFlyTable[index].id == item.id) {
                console.log(111111111111111,item,JSON.stringify(item.geometry.coordinates));
                window.coordinates = JSON.stringify(item.geometry.coordinates);
                isFind = true;
                $.ajax({
                    url: "/one/scene/navigation/route",
                    type: "PUT",
                    dataType: "json",
                    contentType: "application/json; charset=UTF-8",
                    data:JSON.stringify({
                        id:item.id,
                        isDefault: item.isDefault,
                        navigationContent:JSON.stringify(item),
                        navigationName:item.name,
                        remark:item.remark,
                        sceneId:that.config.sceneId
                    }),
                    success: function(result){
                        if (result.errorCode === '401') {
                            loginStatusIntercept(result.msg)
                            return
                        }
                        if(result.errorCode==0){
                            layer.msg("保存成功");
                            that.getList();
                        }else{
                            layer.msg(result.msg||"保存失败");
                        }
                    }
                })
                break;
            }
        }
        //新增飞行路径
        if (!isFind){
            console.log(22222222222);
             $.ajax({
                url: "/one/scene/navigation/route",
                type: "POST",
                dataType: "json",
                contentType: "application/json; charset=UTF-8",
                data:JSON.stringify({
                    isDefault: false,
                    navigationContent:JSON.stringify(item),
                    navigationName:item.name,
                    remark:item.remark,
                    sceneId:that.config.sceneId
                }),
                success: function(result){
                    if (result.errorCode === '401') {
                        loginStatusIntercept(result.msg)
                        return
                    }
                    if(result.errorCode==0){
                        layer.msg("保存成功");
                        that.getList();
                    }else{
                        layer.msg(result.msg||"保存失败");
                    }
                }
            });
        }
    },
    toRoamFly: function (data) {
        mars3d.widget.activate({
            uri: 'widgets/roamFly/widget.js',
            data: data
        });
    }

}));
